"use client";

import React, { useState, useEffect } from "react";
import { Card, Tabs, List, Checkbox, Button, message } from "antd";
import { CheckOutlined } from "@ant-design/icons";
import "./index.css";

const { TabPane } = Tabs;

interface CategoryItem {
    id: string;
    name: string;
    description: string;
    children?: CategoryItem[];
}

interface FrontEndProps {
    onStartPractice: (selectedIds: string[]) => void;
}

const FrontEnd: React.FC<FrontEndProps> = ({ onStartPractice }) => {
    const [activeTab, setActiveTab] = useState<string>("1");
    const [categories, setCategories] = useState<CategoryItem[]>([]);
    const [selectedItems, setSelectedItems] = useState<string[]>([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        fetchCategories();
    }, []);

    const fetchCategories = async () => {
        setLoading(true);
        try {
            // 模拟API调用
            const mockCategories: CategoryItem[] = [
                {
                    id: "1",
                    name: "HTML/CSS",
                    description: "HTML和CSS基础知识",
                    children: [
                        {
                            id: "1-1",
                            name: "HTML基础",
                            description: "HTML标签和属性",
                        },
                        {
                            id: "1-2",
                            name: "CSS选择器",
                            description: "CSS选择器和样式规则",
                        },
                        {
                            id: "1-3",
                            name: "布局",
                            description: "Flex和Grid布局",
                        },
                    ],
                },
                {
                    id: "2",
                    name: "JavaScript",
                    description: "JavaScript编程基础",
                    children: [
                        {
                            id: "2-1",
                            name: "基础语法",
                            description: "变量、数据类型、运算符",
                        },
                        {
                            id: "2-2",
                            name: "函数",
                            description: "函数定义和调用",
                        },
                        {
                            id: "2-3",
                            name: "DOM操作",
                            description: "DOM元素操作和事件处理",
                        },
                    ],
                },
                {
                    id: "3",
                    name: "React",
                    description: "React框架学习",
                    children: [
                        {
                            id: "3-1",
                            name: "组件",
                            description: "组件创建和生命周期",
                        },
                        {
                            id: "3-2",
                            name: "Hooks",
                            description: "React Hooks使用",
                        },
                        {
                            id: "3-3",
                            name: "状态管理",
                            description: "Redux和Context API",
                        },
                    ],
                },
            ];
            setCategories(mockCategories);
        } catch (error) {
            message.error("获取分类失败");
        } finally {
            setLoading(false);
        }
    };

    const handleTabChange = (key: string) => {
        setActiveTab(key);
    };

    const handleCheckboxChange = (id: string) => {
        setSelectedItems((prev) => {
            if (prev.includes(id)) {
                return prev.filter((item) => item !== id);
            }
            return [...prev, id];
        });
    };

    const handleSelectAll = (checked: boolean) => {
        const currentCategory = categories.find((cat) => cat.id === activeTab);
        if (checked && currentCategory?.children) {
            setSelectedItems(currentCategory.children.map((child) => child.id));
        } else {
            setSelectedItems([]);
        }
    };

    const handleStartPractice = () => {
        if (selectedItems.length === 0) {
            message.warning("请至少选择一个练习项目");
            return;
        }
        onStartPractice(selectedItems);
    };

    return (
        <div className="front-end-box">
            <Card loading={loading}>
                <Tabs activeKey={activeTab} onChange={handleTabChange}>
                    {categories.map((category) => (
                        <TabPane tab={category.name} key={category.id}>
                            <div className="category-header">
                                <h3>{category.name}</h3>
                                <p>{category.description}</p>
                                <Checkbox
                                    onChange={(e) =>
                                        handleSelectAll(e.target.checked)
                                    }
                                    checked={category.children?.every((child) =>
                                        selectedItems.includes(child.id)
                                    )}
                                >
                                    全选
                                </Checkbox>
                            </div>
                            <List
                                dataSource={category.children}
                                renderItem={(item) => (
                                    <List.Item
                                        actions={[
                                            <Checkbox
                                                key="checkbox"
                                                checked={selectedItems.includes(
                                                    item.id
                                                )}
                                                onChange={() =>
                                                    handleCheckboxChange(
                                                        item.id
                                                    )
                                                }
                                            />,
                                        ]}
                                    >
                                        <List.Item.Meta
                                            title={item.name}
                                            description={item.description}
                                        />
                                    </List.Item>
                                )}
                            />
                        </TabPane>
                    ))}
                </Tabs>
                <div className="practice-footer">
                    <Button
                        type="primary"
                        icon={<CheckOutlined />}
                        onClick={handleStartPractice}
                        disabled={selectedItems.length === 0}
                    >
                        开始练习 ({selectedItems.length})
                    </Button>
                </div>
            </Card>
        </div>
    );
};

export default FrontEnd;
